import axios from "axios";
import qs from 'querystring';
let baseUrl = '/api'

//引入路由拦截
import router from "@/router";
//请求拦截
axios.interceptors.request.use(req=>{
    if (req.url == '/api/userlogin') {
        return req
    }else{
        //全局添加token请求头
        req.headers.authorization = sessionStorage.getItem('userinfo') ? JSON.parse(sessionStorage.getItem('userinfo')).token : null;
        return req
    }
});
//响应拦截
axios.interceptors.response.use(res=>{
    //全局拦截错误
    if (res.data.msg == '请设置请求头,并携带验证字符串') {
        //没有添加请求头
        //强制它重新登录
        router.push('/login')
    }
    if (res.data.msg == '登录已过期或访问权限受限') {
        //token过期或者失效 要强制跳转到登录
        router.push("/login");
    }
    return res.data
})

//get封装
export const get = (url,params={})=>{
    return new Promise((resolve,reject)=>{
        axios.get(baseUrl+url,{
            params
        }).then(res=>resolve(res))
          .catch(err=>reject(err))
    })
}
//post封装
export const post = (url,params={},isFile=false)=>{
    let data = {};
    //有文件上传
    if(isFile){
        data = new FormData()
        for(let i in params){
            data.append(i,params[i])
        }
    }else{
        //没有上传文件
        data = qs.stringify(params)
    };
    //无文件上传
    return new Promise((resolve,reject)=>{
        axios.post(baseUrl+url,data)
          .then(res=>resolve(res))
          .catch(err=>reject(err))
    })
}